package com.kkb.controller;

import com.kkb.service.impl.AdminServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

@Controller
public class LoginController {

    @Resource
    private AdminServiceImpl adminsService;

    @RequestMapping(value = "login.do")
    public ModelAndView login(String adminName, String adminPwd,HttpServletRequest request) throws UnsupportedEncodingException {
        ModelAndView modelAndView = new ModelAndView();
        if (adminName == null ||adminPwd == null) {
            modelAndView.setViewName("Fail");
            System.out.println("密码或用户名为空");
            return modelAndView;
        }
        boolean match = adminsService.isMatch(adminName, adminPwd);
        if (!match) {
            modelAndView.setViewName("Fail");
            System.out.println("密码和用户名不匹配");
            return modelAndView;
        }
        modelAndView.addObject(adminName,adminName);
        modelAndView.addObject(adminPwd,adminPwd);
        request.setCharacterEncoding("utf-8");
        request.getSession().setAttribute(adminName,adminName);
        request.getSession().setAttribute(adminPwd,adminPwd);
        System.out.println("用户存在，已登录");
        modelAndView.setViewName("index");
        return modelAndView;
    }

    @RequestMapping("loginout.do")
    public ModelAndView loginout(HttpServletRequest req) throws UnsupportedEncodingException {
        req.setCharacterEncoding("utf-8");
        req.getSession().setMaxInactiveInterval(0);
        ModelAndView modelAndView = new ModelAndView();
        System.out.println("用户退出登录，返回登录页面");
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @RequestMapping("back.do")
    public ModelAndView backHome(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login");
        return modelAndView;
    }

}
